import { CommonModule } from '@angular/common';
import { Component, HostListener } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent {

  dataList: any[] = []; // 原始数据

  showList: any[] = []; // 可视数据
  screenHeight = window.innerHeight;
  itemHeight = 30;

  offset = 0; // 便宜量
  listHeight = 0; // 列表高度
  itemNum = 0;  // 可视列表数
  bufferNum = 5; // 缓冲区数量
  dataStartIndex = 0;
  dataEndIndex = 0;
  startIndex = 0;
  endIndex = 0;

  constructor() {
    console.log('screenHeight', this.screenHeight)
    this.getData();
  }
  getData() {
    for (let i = 0; i < 1000000; i++) {
      this.dataList.push(i + 1);
    }
    this.updateRender();
  }

  get container() {
    return document.querySelector('.virtual-container');
  }

  ngAfterViewInit(): void {
    this.container?.addEventListener('scroll', (e: any) => {
      this.updateRender();
    });
  }

  /** 更新渲染 */
  updateRender() {
    this.listHeight = this.dataList.length * this.itemHeight;
    this.itemNum = Math.ceil(this.screenHeight / this.itemHeight);
    const scrollTop = this.container?.scrollTop || 0;
    this.dataStartIndex = Math.floor(scrollTop / this.itemHeight);
    this.dataEndIndex = Math.min(this.dataList.length, this.dataStartIndex + this.itemNum);
    this.startIndex = Math.max(0, this.dataStartIndex - this.bufferNum);
    this.endIndex = Math.min(this.dataList.length, this.dataEndIndex + this.bufferNum);
    this.showList = this.dataList.slice(this.startIndex, this.endIndex);
    this.offset = this.startIndex * this.itemHeight;
  }
}
